<template>
	<view class="y-flex y-flex-1 position-relative" style="background-color: rgba(0,0,0,.2);">
		<view class="y-flex y-flex-1 position-relative">
			<video
			v-if="detail.src"
			is-live
			autoplay
			ref="video"
			class="y-flex-1"
			enable-play-gesture
			:enable-danmu="barrages.length > 0"
			:controls="false"
			:poster="detail.cover"
			:danmu-list="barrages"
			:title="detail.title"
			:src="detail.src"
			@ended="handleEnded"
			@play="handlePlay"
			@pause="handlePause"
			@timeupdate="handleTimeupdate"
			@fullscreenchange="handleFullscreenChange"
			@error="handleError">
				<view class="position-absolute-cover y-flex y-align-center y-justify-center" v-if="playend">
					<text class="fs-28 fr-fff">直播结束</text>
				</view>
				<view class="position-absolute-cover y-flex y-align-center y-justify-center" v-else-if="error">
					<text class="fs-28 fr-fff" @tap="handleCopy(detail.src)">加载失败：{{detail.src}}</text>
				</view>
				<view class="position-absolute-cover" v-else @tap="handleToggle"></view>
				<view class="y-flex position-absolute left-0 right-0 page-padding-gap pt-30 pb-30"
				:class="{'bottom-60': components.length > 0 || cell, 'bottom-0': components.length == 0 && !cell }">
					<view class="y-flex y-row y-align-center">
						<com-icon :name="paused ? 'play_fill' : 'stop'" class="mr-20" size="45" color="#fff" @click="handleToggle"></com-icon>
						<text class="fr-fff fs-35 y-flex-1">直播中 · {{_timeFormat(currentTime)}}</text>
						<template v-if="fullscreen">
							<com-icon name="return" color="#fff" size="40" @click="handleChangeFull(0)"></com-icon>
						</template>
						<template v-else>
							<com-icon class="mr-30" name="full" color="#fff" size="40" @click="handleChangeFull(-90)"></com-icon>
							<com-icon name="mobile" color="#fff" size="40" @click="handleChangeFull(0)"></com-icon>
						</template>
					</view>
					<com-safe-bottom></com-safe-bottom>
				</view>
			</video>
			<view class="position-absolute left-0 right-0 y-flex" :style="{
				'padding-left': pageMarginGap,
				'padding-right': pageMarginGap,
				'bottom': '240rpx'
			}">
				<com-text class="mt-10" line-height="35" size="26" lines="1" :color="skinColor.color_white" :value="detail.subtitle" v-if="detail.subtitle"></com-text>
				<com-text class="mt-10" line-height="35" size="26" lines="5" :color="skinColor.color_white" :value="detail.description" v-if="detail.description"></com-text>
				<scroll-view class="y-flex y-row y-align-center mt-10" :show-scrollbar="false" scroll-x v-if="detail.tags && detail.tags.length > 0">
					<view class="find_novel_tag mr-20 border-color-fff" v-for="(item, index) in detail.tags" :key="index" @tap="handleTagTap(item)">
						<text class="fs-24 fr-fff">{{item.title}}</text>
					</view>
				</scroll-view>
			</view>
		</view>
		<view class="position-absolute bottom-0 left-0 right-0 y-flex" v-if="components.length > 0 || cell">
			<view class="y-flex y-row y-align-center y-justify-center mb-40 opac-6" @tap="handleShowModal">
				<com-icon name="fold" size="24" :color="skinColor.color_white"></com-icon>
				<text class="fs-20 ml-10" :style="{color: skinColor.color_white}">点击查看更多</text>
			</view>
			<com-safe-bottom></com-safe-bottom>
		</view>
		<com-popup position="absolute" :visible.sync="modalShow" direction="bottom" @hide="handleModalHide">
			<view class="y-flex" :style="{'background-color': skinColor.color_bg_1, 'height': modalHeight + 'px'}">
				<module-list
				ref="list"
				:params="modalParams"
				:data="components"
				:cell="cell"
				:bounce="pageStyle.enableBounce"
				:back-top-show="pageStyle.enableBackTop"
				:refreshImage="pageStyle.pulldownRefreshImage"
				:pulldownable="pageStyle.enablePulldown == 1"
				:loadmoreable="pageStyle.enableLoadmore == 1"
				:loadingColor="pageStyle.loadingColor"
				:backTopImage="pageStyle.backTopImage"
				:marginGap="pageStyle.pageMarginGap"
				:showTopGap="components.length == 0"
				@pulldown="handleModalPulldown">
				</module-list>
			</view>
		</com-popup>
	</view>
</template>

<script>
	import { setWallpaper } from '@/assets/js/native.js'
	import { timeFormat } from '@/assets/js/util.js'
	import { openDB, closeDB, select, insert, update, remove } from '@/assets/database'
	import ModuleList from './components/ModuleList.vue' 
	export default {
		inject: ['getPage', 'getPageStyle', 'getSkinColor', 'getQuery', 'navigate', 'confirm'],
		components: {ModuleList},
		computed: {
			history () {
				return this.$store.getters['setting/GET_HISTORY']
			},
			skinColor () {
				return this.getSkinColor()
			},
			app () {
				return getApp().globalData
			},
			network () {
				return this.$store.getters['network/GET']
			},
			//获取路由参数
			query () {
				return this.getQuery()
			},
			page () {
				return this.getPage()
			},
			pageStyle () {
				return this.getPageStyle()
			},
			//页面左右边距
			pageMarginGap () {
				return this.app.$utils.pixelunit(this.pageStyle?.pageMarginGap)
			},
			cell () {
				return this.page?.comments || this.page?.cell || null
			},
			components () {
				return this.page?.components || []
			}
		},
		data () {
			return {
				detail: {},//详情信息
				barrages: [],//图片集合
				currentTime: 0,//播放时间
				playend: false,//播放结束
				error: false,//加载失败
				fullscreen: false,//全屏
				paused: true,//暂停
				modalShow: false,//更多模块展示
				modalHeight: 0,
				modalParams: {}
			}
		},
		mounted () {
			this.$nextTick(this.handlePulldown)
		},
		methods: {
			onBackPress () {
				if ( this.actionShow ) {
					this.actionShow = false
					return true
				}
				if ( this.modalShow ) {
					this.modalShow = false
					return true
				}
				if ( this.detail.uniqueId ) {
					if ( this.history == 0 ) {
						this.confirm({
							title: '记录提示',
							content: '是否记录当前直播？',
							cancelText: '取消记录',
							confirmText: '保存记录',
							success: res => {
								if ( res.confirm ) {
									this.saveRecord()
								} else {
									this.app.$Router.back()
								}
							}
						})
					} else if ( this.history == 1 ) this.saveRecord()
					else this.app.$Router.back()
					return true
				}
				return false
			},
			async saveRecord () {
				try{
					await openDB()
					if ( this.record.id ) {
						await update('record', {
							url: this.detail.url,
							title: this.detail.title || '',
							cover: this.detail.cover || '',
							is_adult: this.detail.isAdult,
							source_id: this.detail.sourceId
						}, 'id = ' + this.record.id)
					} else {
						await insert('record', {
							unique_id: this.detail.uniqueId,
							url: this.detail.url,
							title: this.detail.title || '',
							cover: this.detail.cover || '',
							is_adult: this.detail.isAdult,
							source_id: this.detail.sourceId
						})
					}
					closeDB()
					this.app.$Router.back()
				}catch(e){
					closeDB()
					uni.showToast({
						title: e.message,
						icon: 'none'
					})
					setTimeout(() => {
						this.app.$Router.back()
					}, 500)
				}
			},
			onShow () {
				if ( this.detail.uniqueId ) this.getRecord()
			},
			async getRecord () {
				try{
					await openDB()
					const data2 = await select('collection', 'unique_id = "' + this.detail.uniqueId + '"')
					const utils = [{
						label: data2.count > 0 ? '已收藏' : '点击收藏',
						icon: data2.count > 0 ? 'favor_fill' : 'favor',
						color: data2.count > 0 ? this.skinColor.color_red : '',
						func: async () => {
							try{
								await openDB()
								if ( data2.count > 0 ) {
									await remove('collection', 'id = ' + data2.list[0].id)
									uni.showToast({
										title: '取消收藏成功',
										icon: 'none'
									})
									await closeDB()
									this.getRecord()
								} else {
									const params = {
										unique_id: this.detail.uniqueId,
										url: this.detail.url,
										title: this.detail.title || '',
										cover: this.detail.cover || '',
										is_adult: this.detail.isAdult || 0,
										source_id: this.detail.sourceId
									}
									await insert('collection', params)
									uni.showToast({
										title: '收藏成功',
										icon: 'none'
									})
									await closeDB()
									this.getRecord()
								}
							}catch(e){
								closeDB()
								uni.showToast({
									title: e.message,
									icon: 'none'
								})
							}
						}
					}]
					if ( this.detail.shareUrl && this.detail.title ) {
						utils.push({
							label: '分享资源',
							icon: 'forward',
							func: () => {
								this.app.$Router.push({
									path: '/pages/find/modules/poster',
									animationType: 'none',
									query: {
										params: this.detail
									}
								})
							}
						})
					}
					this.$emit('utils', utils)
				}catch(e){
					uni.showToast({
						title: e.message,
						icon: 'none'
					})
				}
				closeDB()
			},
			async handlePulldown (callback) {
				try{
					this.detail = await this.handleGetDetail()
					this.barrages = await this.handleGetBarrages()
					if ( this.detail.uniqueId ) this.getRecord()
					this.$emit('loaded', true)
				}catch(e){
					this.$emit('loaded', true)
				}
			},
			async handleGetDetail () {
				const detail = this.page?.detail || {}
				const staticData = this.network.staticDataHandle(detail.staticData || {}, this.query)
				const dynamicData = detail.dynamicData
				const request = detail.request
				let data = {}
				if ( dynamicData && request ) {
					const newRequest = this.network.requestHandle(request, this.query)
					const response = await this.network.$request(newRequest)
					data = await this.network.$list(dynamicData, response)
					data.uniqueId = data.id || this.network.getUniqueId(newRequest)
					if ( !data.shareUrl && !staticData.shareUrl ) data.shareUrl = await this.network.getShareUrl(newRequest)
				}
				return Object.assign({}, staticData, data)
			},
			async handleGetBarrages () {
				const items = this.page?.barrages || {}
				const params = Object.assign({}, this.query, this.detail)
				const staticData = items.staticData ? this.network.staticDataHandle(items.staticData, params) : []
				const dynamicData = items.dynamicData
				const request = items.request
				let data = []
				if ( dynamicData && request ) {
					const newRequest = this.network.requestHandle(request, params)
					const response = await this.network.$request(newRequest)
					data = await this.network.$list(dynamicData, response)
				}
				return staticData.concat(data)
			},
			handleTagTap (item) {
				this.navigate(item.url)
			},
			handleShowModal () {
				const system = uni.getSystemInfoSync()
				this.modalHeight = system.windowHeight - uni.upx2px(100) - system.safeArea.top
				this.modalShow = true
				this.$emit('scroll', 200)
				this.$nextTick(function () {
					this.handleModalPulldown()
				})
			},
			handleModalHide () {
				this.modalShow = false
				this.$emit('scroll', 0)
			},
			handleModalPulldown (callback) {
				this.modalParams = Object.assign({}, this.query, this.detail)
				this.$refs.list && this.$refs.list.initModule(callback, callback ? true : false)
			},
			handleCopy (src) {
				copyText(src)
			},
			handlePlay (index) {
				this.paused = false
			},
			handlePause (index) {
				this.paused = true
			},
			handleError (e) {
				this.error = true
			},
			handleEnded () {
				this.playend = true
			},
			handleTimeupdate (e) {
				this.currentTime = e.detail.currentTime
			},
			handleFullscreenChange (e) {
				this.fullscreen = e.detail.fullScreen
			},
			handleToggle () {
				if ( this.$refs.video ) {
					if ( this.paused ) this.$refs.video.play()
					else this.$refs.video.pause()
				}
			},
			handleChangeFull (direction) {
				if ( this.$refs.video ) {
					if ( this.fullscreen ) this.$refs.video.exitFullScreen()
					else this.$refs.video.requestFullScreen({direction: direction || 0})
				}
			},
			_timeFormat (time) {
				return timeFormat(time, 'mm:ss')
			}
		}
	}
</script>

<style>
	.find_novel_tag {
		border-width: 1px;
		border-style: solid;
		border-radius: 5rpx;
		padding: 4rpx 10rpx;
	}
</style>